import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-weixin-wx-pay',
	templateUrl: './wx-pay.component.html',
})
export class WXPayComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberInput: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择车牌号码'
					}
				}
			},
		}
	}
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	tableSearch:any = {
		searchKey:'',
		dataType:'1',
		tradeState:"SUCCESS",
		feeType:'', // 费用类型
		payType:'', // 支付类型
	}
	startTime:string = '';
	endTime:string = '';
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	deviceId:string = '';
	carNumber:string = '';
	delLimit:boolean = false;
	editOrder:any={
		payType:"0",
		feeTypes:"0",
		remark:""
	}
	typeExpenseBack:string='0'

	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage||1;
		});
	}
	//初始化权限按钮
	initBtn() {
		let param = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_contract:wx:pay')));
		if(param){
			for(let item of param) {
				if(item.sourceKey === "wx:pay:del" && item.parentId) {
					this.delLimit = true;
				};
			}
		}
	}
	// 接收子组件传递过来的数据
	getSelectTableTime(time){
		this.startTime = time.startTime;
		this.endTime = time.endTime;
	}
	ngOnInit(){
		this.initBtn();
		this.load();
		// System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
		// 	System.import('assets/js/select2-zh-CN.js').then(()=>{
		// 		this.selectCompany().then(()=>{
		// 			$('.select2-selection__placeholder').text(this.projectCarFrom.carNumber).animate({'color':'#555'},10);
		// 		});//初始化select 2 车辆
		// 	})

		// })
	}
	//table刷新
    refresh(){
    	this.load();
    }
	//表格搜索
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load(){
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId:this.selectedCompanyId,
				deviceId:this.deviceId,
//				carNumber:this.carNumber,
				startTime:this.startTime,
				endTime:this.endTime,
				dataType:this.tableSearch.dataType,
				searchKey:common.stringTrim(this.tableSearch.searchKey),
				feeTypes:this.tableSearch.feeType,
				payType:this.tableSearch.payType,
				tradeState:this.tableSearch.tradeState,
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("payOrder/queryWXMiniDeviceOrderByParam.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}
	//报表导出
	exportTable(){
		const param = {
			dataType:this.tableSearch.dataType,
			'startTime':this.startTime,
			'endTime':this.endTime,
			'companyId':this.selectedCompanyId,
			'carNumber':this.carNumber,
			'searchKey':this.tableSearch.searchKey.trim(),
			'feeTypes':this.tableSearch.feeType,
			'payType':this.tableSearch.payType,
			'tradeState':this.tableSearch.tradeState,
		};
		let timeCheck = common.correctTime(param, ['dataType', 'tradeState'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(param, 'param', config.BaseURL + 'payOrder/exportWXDeviceOrderList.html')
	}
	//删除
	delRow(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http("payOrder/deleteWXMiniDeviceOrderById.html",'id='+row.id).subscribe(data=>{
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
	//选择公司
	// selectCompany() {
	// 	var that = this;
	// 	return new Promise(function (resolve, reject) {
	// 	$("#carNumberSelectInput").select2({
	// 		language: "zh-CN",
	// 		placeholder: "请选择",
	// 		allowClear: true,
	// 		minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
	// 		ajax: {
	// 			url: config.BaseURL + "stats/carListByCarNumber.html",
	// 			dataType: 'json',
	// 			delay: 50,
	// 			method: "POST",
	// 			xhrFields: {
	// 				withCredentials: true
	// 			},
	// 			data: function(params) {
	// 				return {
	// 					"carNumber": params.term // search term
	// 				};
	// 			},
	// 			processResults: function(data, params) {
	// 				var options = new Array();
	// 				// 小于10个数量才判断重复
	// 				if(data.data.length<=10){
	// 					let arr = []
	// 					let sameCar = []
	// 					// 判断相同的车牌号
	// 					for (let index = 0; index < data.data.length; index++) {
	// 						let car = data.data[index];
	// 						if(arr.indexOf(car.carNumber)!=-1){
	// 							sameCar.push(car.carNumber)
	// 						}else{
	// 							arr.push(car.carNumber);
	// 						}
	// 					}
	// 					$(data.data).each(function(index, car) {
	// 						if(sameCar.indexOf(car.carNumber)!=-1){
	// 							options.push({
	// 								id: car.deviceId,
	// 								text: car.carNumber+"["+car.parentName+"]"
	// 							})
	// 						}else{
	// 							options.push({
	// 								id: car.deviceId,
	// 								text: car.carNumber
	// 							})
	// 						}
	// 					});
	// 				}else{
	// 					$(data.data).each(function(index, car) {
	// 						options.push({
	// 							id: car.deviceId,
	// 							text: car.carNumber
	// 						})
	// 					});
	// 				}
	// 				return {
	// 					results: options //获取查询后的结果
	// 				};
	// 			},
	// 			cache: true
	// 		},
	// 		templateResult: that.formatRepo
	// 	}).on("select2:select", function(e) {
	// 		var data = e.params.data;
	// 		that.projectCarFrom.deviceId = data.id;
	// 		if(data.text.indexOf('[') > 0){
	// 			that.projectCarFrom.carNumber = data.text.split('[')[0];
	// 		} else {
	// 			that.projectCarFrom.carNumber = data.text;
	// 		}
	// 		$("#carNumberInput").val(that.projectCarFrom.carNumber).change();
	// 	});
	// 		resolve();
	// 	})

	// }
	//select2 格式回调函数
	// formatRepo(state) {
	// 	if(!state.id) {
	// 		return state.text;
	// 	}
	// 	var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
	// 	return $state;
	// }
	// 编辑车牌
	// editRow(row,modal){
	// 	modal.show();
	// 	this.projectCarFrom.deviceId = row.deviceId;
	// 	this.projectCarFrom.carNumber = row.goodsName;
	// 	this.rowId = row.id;
	// 	var str=$("<span class='select2-selection__placeholder'>"+ row.goodsName +"</span>");
	// 	$("#select2-carNumberSelectInput-container").empty();
	// 	$("#select2-carNumberSelectInput-container").attr("title",row.goodsName);
	// 	$("#select2-carNumberSelectInput-container").prepend(str);
	// 	$("#projectCarFrom").data('bootstrapValidator').resetForm();
	// }
	// 编辑备注
	editRow(row,modal){
		modal.show();
		this.editOrder.remark = row.remark;
		this.editOrder.payType = row.payType || '0';
		this.editOrder.feeTypes = row.feeTypes;
		this.typeExpenseBack = row.feeTypes;
		this.rowId = row.id;
	}
	payTypeChange(val){
		this.editOrder.payType = val;
		if(val == 0){
			this.editOrder.feeTypes = this.typeExpenseBack
		}else{
			this.editOrder.feeTypes = "0"
		}
	}

	typeExpenseChange(val){
		this.editOrder.feeTypes= val
		if(this.editOrder.payType==0){
			this.typeExpenseBack=this.editOrder.feeTypes
		}
	}



	projectCarFrom: any={
		// deviceId: '',
		// carNumber: ''
		remark: ''
	}
	rowId: any = '';
	//清除车辆选中值
	// del_carNumber2(){
	// 	this.projectCarFrom.deviceId = '';
	// 	this.projectCarFrom.carNumber = '';
	// 	var str=$("<span class='select2-selection__placeholder'>请选择</span>");
	// 	$('#carNumberInput').val("").change();
	// 	$('#carNumberSelectInput').val("");
	// 	$("#select2-carNumberSelectInput-container").empty();
	// 	$("#select2-carNumberSelectInput-container").attr("title","");
	// 	$("#select2-carNumberSelectInput-container").prepend(str);
	// 	$("#projectCarFrom").data('bootstrapValidator').resetForm();
	// }
	projectCarClose(modal){
		// this.projectCarFrom.deviceId = '';
		// this.projectCarFrom.carNumber = '';
		this.projectCarFrom.remark = '';
		modal.hide();
	}
	projectCarSubmit(modal){
		// $('#projectCarFrom').bootstrapValidator('validate'); //开启验证
		// let isValid = $('#projectCarFrom').data('bootstrapValidator').isValid();  //验证是否通过

		// var reqData = {
		// 	deviceId: this.projectCarFrom.deviceId,
		// 	id: this.rowId
		// }
		// if(isValid){
		// 	if(!this.projectCarFrom.deviceId){
		// 		this.jsonApiService.message('该车暂无设备ID');
		// 		return;
		// 	}
		// 	this.jsonApiService.http_obj('payOrder/editPayOrderByParam.html',reqData).subscribe(data=> {
		// 		this.jsonApiService.message(data.message);
		// 		if(data.success){
		// 			this.load();
		// 			this.projectCarClose(modal);
		// 		}
		// 	});
		// }


		var reqData = {
			id: this.rowId,
			...this.editOrder
		}
		this.jsonApiService.http_obj('payOrder/editPayOrderRemark.html',reqData).subscribe(data=> {
			this.jsonApiService.message(data.message);
			if(data.success){
				this.load();
				this.projectCarClose(modal);
			}
		});
	}
}